#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/Callbacks.h"
#include "include/muduo/net/TcpClient.h"
#include "include/muduo/base/CountDownLatch.h"

#include <iostream>
#include <unordered_map>
class TranslateClient{
public:
    TranslateClient(const std::string& ip, int port)
    :_latch(1), _client(_loopthread.startLoop(), muduo::net::InetAddress(ip, port), "Translateclient")
    {
        // 设置建立连接时的回调函数
        _client.setConnectionCallback(std::bind(&TranslateClient::OnConection, this, std::placeholders::_1));
        // 设置收到消息时的回调函数
        _client.setMessageCallback(std::bind(&TranslateClient::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void connect(){
        _client.connect();
        _latch.wait();
    }
    bool send(const std::string& msg){
        if(_conn->connected()){
            _conn->send(msg);
            return true;
        }
        return false;
    }
private:
    void OnConection(const muduo::net::TcpConnectionPtr& conn){
        // 新连接尽力成功时的回调函数
        if(conn->connected()){
            _latch.countDown();
            _conn = conn;
        }else{
            // nothing to do
            _conn.reset();
        }
    }
    void OnMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp){
        // 通信连接收到请求时的回调函数
        std::cout << "翻译结果:" << buf->retrieveAllAsString() << std::endl;
    }
private:
    muduo::CountDownLatch _latch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};
int main()
{
    TranslateClient client("127.0.0.1", 8080);
    client.connect();
    while(1){
        std::string buffer;
        std::cin >> buffer;
        client.send(buffer);
    }
    return 0;
}
